// 本地存储工具类

// 存储键名常量
const STORAGE_KEYS = {
  PLAYER_PROGRESS: 'chess_tower_defense_progress',
  GAME_SETTINGS: 'chess_tower_defense_settings',
  ACHIEVEMENTS: 'chess_tower_defense_achievements',
  STATISTICS: 'chess_tower_defense_statistics'
} as const;

// 玩家进度数据结构
export interface PlayerProgress {
  levels: Record<string, LevelProgress>;
  totalScore: number;
  totalPlayTime: number;
  totalMoodValue: number;
  unlockedLevels: string[];
  lastPlayedLevel: string | null;
  createdAt: number;
  updatedAt: number;
}

// 关卡进度数据结构
export interface LevelProgress {
  levelId: string;
  bestScore: number;
  bestTime: number;
  stars: number;
  completed: boolean;
  attempts: number;
  firstCompletedAt: number | null;
  lastPlayedAt: number;
  statistics: LevelStatistics;
}

// 关卡统计数据
export interface LevelStatistics {
  totalUnitsDeployed: number;
  totalEnemiesDefeated: number;
  totalSkillsUsed: number;
  totalMoodCollected: number;
  maxWaveReached: number;
  averageHealthRemaining: number;
}

// 游戏设置数据结构
export interface GameSettings {
  soundEnabled: boolean;
  musicEnabled: boolean;
  soundVolume: number;
  musicVolume: number;
  gameSpeed: number;
  showTutorial: boolean;
  language: string;
  theme: 'light' | 'dark' | 'auto';
}

// 成就数据结构
export interface Achievement {
  id: string;
  name: string;
  description: string;
  icon: string;
  unlocked: boolean;
  unlockedAt: number | null;
  progress: number;
  maxProgress: number;
  category: 'combat' | 'collection' | 'skill' | 'time' | 'special';
  rarity: 'common' | 'rare' | 'epic' | 'legendary';
}

// 游戏统计数据
export interface GameStatistics {
  totalGamesPlayed: number;
  totalGamesWon: number;
  totalPlayTime: number;
  totalScore: number;
  totalUnitsDeployed: number;
  totalEnemiesDefeated: number;
  totalSkillsUsed: number;
  totalMoodCollected: number;
  favoriteUnit: string;
  favoriteSkill: string;
  longestPlaySession: number;
  highestScore: number;
  fastestCompletion: number;
}

// 星级评价计算器
export class StarRatingCalculator {
  // 计算关卡星级评价
  static calculateStars(
    levelId: string,
    gameResult: {
      completed: boolean;
      score: number;
      time: number; // 毫秒
      healthRemaining: number;
      maxHealth: number;
      unitsUsed: number;
      skillsUsed: number;
      moodCollected: number;
      waveReached: number;
      maxWave: number;
    }
  ): { stars: number; breakdown: Record<string, number>; totalScore: number } {
    if (!gameResult.completed) {
      return { stars: 0, breakdown: {}, totalScore: 0 };
    }

    const breakdown: Record<string, number> = {};
    let totalScore = 0;

    // 基础完成分数 (30%)
    const completionScore = 300;
    breakdown.completion = completionScore;
    totalScore += completionScore;

    // 时间奖励 (25%)
    const timeScore = this.calculateTimeScore(gameResult.time, levelId);
    breakdown.time = timeScore;
    totalScore += timeScore;

    // 生命值奖励 (20%)
    const healthScore = this.calculateHealthScore(
      gameResult.healthRemaining,
      gameResult.maxHealth
    );
    breakdown.health = healthScore;
    totalScore += healthScore;

    // 效率奖励 (15%)
    const efficiencyScore = this.calculateEfficiencyScore(
      gameResult.unitsUsed,
      gameResult.skillsUsed,
      gameResult.waveReached
    );
    breakdown.efficiency = efficiencyScore;
    totalScore += efficiencyScore;

    // 意境收集奖励 (10%)
    const moodScore = this.calculateMoodScore(gameResult.moodCollected);
    breakdown.mood = moodScore;
    totalScore += moodScore;

    // 计算星级
    const stars = this.scoreToStars(totalScore);

    return { stars, breakdown, totalScore };
  }

  // 时间分数计算
  private static calculateTimeScore(actualTime: number, levelId: string): number {
    // 根据关卡设定目标时间
    const targetTimes: Record<string, number> = {
      'level-1': 180000, // 3分钟
      'level-2': 240000, // 4分钟
      'level-3': 300000, // 5分钟
      'level-4': 360000, // 6分钟
      'level-5': 420000, // 7分钟
    };

    const targetTime = targetTimes[levelId] || 300000; // 默认5分钟
    const timeRatio = Math.min(1, targetTime / actualTime);
    
    return Math.floor(250 * timeRatio); // 最高250分
  }

  // 生命值分数计算
  private static calculateHealthScore(remaining: number, max: number): number {
    const healthRatio = remaining / max;
    return Math.floor(200 * healthRatio); // 最高200分
  }

  // 效率分数计算
  private static calculateEfficiencyScore(
    unitsUsed: number,
    skillsUsed: number,
    waveReached: number
  ): number {
    // 基于单位使用效率和技能使用效率
    const unitEfficiency = Math.max(0, 1 - (unitsUsed - 10) / 20); // 10个单位为基准
    const skillEfficiency = Math.max(0, 1 - (skillsUsed - 5) / 10); // 5个技能为基准
    
    const averageEfficiency = (unitEfficiency + skillEfficiency) / 2;
    return Math.floor(150 * averageEfficiency); // 最高150分
  }

  // 意境收集分数计算
  private static calculateMoodScore(moodCollected: number): number {
    // 每收集1点意境值获得2分，最高100分
    return Math.min(100, moodCollected * 2);
  }

  // 分数转星级
  private static scoreToStars(totalScore: number): number {
    if (totalScore >= 900) return 3; // 3星：90%以上
    if (totalScore >= 700) return 2; // 2星：70%以上
    if (totalScore >= 500) return 1; // 1星：50%以上
    return 0; // 0星：未达标
  }
}

// 本地存储管理器
export class StorageManager {
  // 获取玩家进度
  static getPlayerProgress(): PlayerProgress {
    try {
      const stored = localStorage.getItem(STORAGE_KEYS.PLAYER_PROGRESS);
      if (stored) {
        return JSON.parse(stored);
      }
    } catch (error) {
      console.error('Failed to load player progress:', error);
    }

    // 返回默认进度
    return this.createDefaultProgress();
  }

  // 保存玩家进度
  static savePlayerProgress(progress: PlayerProgress): boolean {
    try {
      progress.updatedAt = Date.now();
      localStorage.setItem(STORAGE_KEYS.PLAYER_PROGRESS, JSON.stringify(progress));
      return true;
    } catch (error) {
      console.error('Failed to save player progress:', error);
      return false;
    }
  }

  // 更新关卡进度
  static updateLevelProgress(
    levelId: string,
    gameResult: {
      completed: boolean;
      score: number;
      time: number;
      healthRemaining: number;
      maxHealth: number;
      unitsUsed: number;
      skillsUsed: number;
      moodCollected: number;
      waveReached: number;
      maxWave: number;
      statistics: LevelStatistics;
    }
  ): { progress: PlayerProgress; levelProgress: LevelProgress; rating: any } {
    const progress = this.getPlayerProgress();
    const currentTime = Date.now();

    // 计算星级评价
    const rating = StarRatingCalculator.calculateStars(levelId, gameResult);

    // 获取或创建关卡进度
    let levelProgress = progress.levels[levelId];
    if (!levelProgress) {
      levelProgress = {
        levelId,
        bestScore: 0,
        bestTime: Infinity,
        stars: 0,
        completed: false,
        attempts: 0,
        firstCompletedAt: null,
        lastPlayedAt: currentTime,
        statistics: {
          totalUnitsDeployed: 0,
          totalEnemiesDefeated: 0,
          totalSkillsUsed: 0,
          totalMoodCollected: 0,
          maxWaveReached: 0,
          averageHealthRemaining: 0
        }
      };
    }

    // 更新关卡进度
    levelProgress.attempts++;
    levelProgress.lastPlayedAt = currentTime;

    if (gameResult.completed) {
      if (!levelProgress.completed) {
        levelProgress.completed = true;
        levelProgress.firstCompletedAt = currentTime;
      }

      // 更新最佳记录
      if (gameResult.score > levelProgress.bestScore) {
        levelProgress.bestScore = gameResult.score;
      }
      if (gameResult.time < levelProgress.bestTime) {
        levelProgress.bestTime = gameResult.time;
      }
      if (rating.stars > levelProgress.stars) {
        levelProgress.stars = rating.stars;
      }
    }

    // 更新统计数据
    levelProgress.statistics.totalUnitsDeployed += gameResult.unitsUsed;
    levelProgress.statistics.totalSkillsUsed += gameResult.skillsUsed;
    levelProgress.statistics.totalMoodCollected += gameResult.moodCollected;
    levelProgress.statistics.maxWaveReached = Math.max(
      levelProgress.statistics.maxWaveReached,
      gameResult.waveReached
    );

    // 更新全局进度
    progress.levels[levelId] = levelProgress;
    progress.totalScore += gameResult.score;
    progress.totalMoodValue += gameResult.moodCollected;
    progress.lastPlayedLevel = levelId;

    // 解锁下一关卡
    if (gameResult.completed && rating.stars >= 1) {
      const nextLevelId = this.getNextLevelId(levelId);
      if (nextLevelId && !progress.unlockedLevels.includes(nextLevelId)) {
        progress.unlockedLevels.push(nextLevelId);
      }
    }

    // 保存进度
    this.savePlayerProgress(progress);

    return { progress, levelProgress, rating };
  }

  // 获取游戏设置
  static getGameSettings(): GameSettings {
    try {
      const stored = localStorage.getItem(STORAGE_KEYS.GAME_SETTINGS);
      if (stored) {
        return { ...this.createDefaultSettings(), ...JSON.parse(stored) };
      }
    } catch (error) {
      console.error('Failed to load game settings:', error);
    }

    return this.createDefaultSettings();
  }

  // 保存游戏设置
  static saveGameSettings(settings: GameSettings): boolean {
    try {
      localStorage.setItem(STORAGE_KEYS.GAME_SETTINGS, JSON.stringify(settings));
      return true;
    } catch (error) {
      console.error('Failed to save game settings:', error);
      return false;
    }
  }

  // 获取游戏统计
  static getGameStatistics(): GameStatistics {
    try {
      const stored = localStorage.getItem(STORAGE_KEYS.STATISTICS);
      if (stored) {
        return JSON.parse(stored);
      }
    } catch (error) {
      console.error('Failed to load game statistics:', error);
    }

    return this.createDefaultStatistics();
  }

  // 更新游戏统计
  static updateGameStatistics(gameData: {
    completed: boolean;
    playTime: number;
    score: number;
    unitsUsed: number;
    skillsUsed: number;
    moodCollected: number;
    favoriteUnit?: string;
    favoriteSkill?: string;
  }): boolean {
    try {
      const stats = this.getGameStatistics();
      
      stats.totalGamesPlayed++;
      if (gameData.completed) {
        stats.totalGamesWon++;
      }
      
      stats.totalPlayTime += gameData.playTime;
      stats.totalScore += gameData.score;
      stats.totalUnitsDeployed += gameData.unitsUsed;
      stats.totalSkillsUsed += gameData.skillsUsed;
      stats.totalMoodCollected += gameData.moodCollected;
      
      if (gameData.score > stats.highestScore) {
        stats.highestScore = gameData.score;
      }
      
      if (gameData.playTime > stats.longestPlaySession) {
        stats.longestPlaySession = gameData.playTime;
      }
      
      if (gameData.favoriteUnit) {
        stats.favoriteUnit = gameData.favoriteUnit;
      }
      
      if (gameData.favoriteSkill) {
        stats.favoriteSkill = gameData.favoriteSkill;
      }
      
      localStorage.setItem(STORAGE_KEYS.STATISTICS, JSON.stringify(stats));
      return true;
    } catch (error) {
      console.error('Failed to update game statistics:', error);
      return false;
    }
  }

  // 清除所有数据
  static clearAllData(): boolean {
    try {
      Object.values(STORAGE_KEYS).forEach(key => {
        localStorage.removeItem(key);
      });
      return true;
    } catch (error) {
      console.error('Failed to clear data:', error);
      return false;
    }
  }

  // 导出数据
  static exportData(): string {
    const data = {
      progress: this.getPlayerProgress(),
      settings: this.getGameSettings(),
      statistics: this.getGameStatistics(),
      exportedAt: Date.now()
    };
    
    return JSON.stringify(data, null, 2);
  }

  // 导入数据
  static importData(jsonData: string): boolean {
    try {
      const data = JSON.parse(jsonData);
      
      if (data.progress) {
        this.savePlayerProgress(data.progress);
      }
      
      if (data.settings) {
        this.saveGameSettings(data.settings);
      }
      
      if (data.statistics) {
        localStorage.setItem(STORAGE_KEYS.STATISTICS, JSON.stringify(data.statistics));
      }
      
      return true;
    } catch (error) {
      console.error('Failed to import data:', error);
      return false;
    }
  }

  // 创建默认进度
  private static createDefaultProgress(): PlayerProgress {
    const now = Date.now();
    return {
      levels: {},
      totalScore: 0,
      totalPlayTime: 0,
      totalMoodValue: 0,
      unlockedLevels: ['level-1'], // 默认解锁第一关
      lastPlayedLevel: null,
      createdAt: now,
      updatedAt: now
    };
  }

  // 创建默认设置
  private static createDefaultSettings(): GameSettings {
    return {
      soundEnabled: true,
      musicEnabled: true,
      soundVolume: 0.7,
      musicVolume: 0.5,
      gameSpeed: 1,
      showTutorial: true,
      language: 'zh-CN',
      theme: 'auto'
    };
  }

  // 创建默认统计
  private static createDefaultStatistics(): GameStatistics {
    return {
      totalGamesPlayed: 0,
      totalGamesWon: 0,
      totalPlayTime: 0,
      totalScore: 0,
      totalUnitsDeployed: 0,
      totalEnemiesDefeated: 0,
      totalSkillsUsed: 0,
      totalMoodCollected: 0,
      favoriteUnit: '',
      favoriteSkill: '',
      longestPlaySession: 0,
      highestScore: 0,
      fastestCompletion: 0
    };
  }

  // 获取下一关卡ID
  private static getNextLevelId(currentLevelId: string): string | null {
    const levelOrder = ['level-1', 'level-2', 'level-3', 'level-4', 'level-5'];
    const currentIndex = levelOrder.indexOf(currentLevelId);
    
    if (currentIndex >= 0 && currentIndex < levelOrder.length - 1) {
      return levelOrder[currentIndex + 1];
    }
    
    return null;
  }
}